//index.js
const app = getApp()
Page({
  data: {
    orderTips: '最快5分钟接驾',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    imgUrls: [
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
    ],
    locationStart: app.globalData.locationStart,
    locationEnd: app.globalData.locationEnd,
    distance: null,
    amount: null,
    publish: false,
    umbrellaArray: [],
    index: 0
  },
  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    });
  },
  onLoad: function() {
    var that = this;
    wx.getStorage({
      key: 'userInfo',
      success: function(res) {
        app.globalData.sessionId = res.data.sessionId;
        app.globalData.phone = res.data.phone;
      }
    });
    wx.request({
      url: 'http://' + app.globalData.host + '/user/umbrella',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      method: 'GET',
      success: function(res) {
        that.setData({
          umbrellaArray: res.data.data
        });

      }
    });
    // 提示应该只出现一次
    if (app.globalData.reLaunch == true) {
      wx.showModal({
        title: '用户许可协议',
        content: '同意此协议才可以继续使用\n具体请浏览www.ddsfs.com',
        success: function(res) {
          if (res.confirm) {
            app.globalData.reLaunch = false;
          } else if (res.cancel) {
            wx.reLaunch({
              url: './index',
            });
          } else {
            wx.reLaunch({
              url: './index',
            });
          }
        }
      });
    }

  },
  user: function() {
    wx.navigateTo({
      url: '/pages/user/userSettings/user',
    });
  },
  // 触发选择起始地点的input
  locationStart: function() {
    // 定位，获取用户所在位置
    wx.chooseLocation({
      success: function(res) {
        // 设置用户的起始位置名，经纬度
        app.globalData.latitudeStart = res.latitude
        app.globalData.longitudeStart = res.longitude
        app.globalData.locationStart = res.name;
      },
    })
  },
  locationEnd: function() {
    if (this.data.locationStart == null) {
      wx.showToast({
        title: '请先选择你当前的位置',
        icon: 'none',
        duration: 2000
      })
    } else {
      // 定位，获取用户所在位置
      wx.chooseLocation({
        success: function(res) {
          // 设置用户的起始位置名，经纬度
          app.globalData.latitudeEnd = res.latitude
          app.globalData.longitudeEnd = res.longitude
          app.globalData.locationEnd = res.name;
        },
      });
    }
  },
  // 加载位置选择成功的页面,当在地图选择页面上点击确认后，要在此函数中加载全局变量
  onShow: function() {
    if (app.globalData.locationEnd == null) {
      var location = {
        locationStart: app.globalData.locationStart,
        locationEnd: app.globalData.locationEnd,
      }
      this.setData(location);
    } else {
      var dis = this.getDistance(app.globalData.latitudeStart, app.globalData.longitudeStart, app.globalData.latitudeEnd, app.globalData.longitudeEnd);
      var location = {
        locationStart: app.globalData.locationStart,
        locationEnd: app.globalData.locationEnd,
        distance: dis,
        amount: (dis * 0.003).toFixed(2)
      }
      // 写入全局变量
      app.globalData.distance = dis;
      this.setData(location);
    }

    if (this.data.publish == true) {
      this.setData({
        locationStart: app.globalData.locationStart,
        locationEnd: app.globalData.locationEnd,
        distance: null,
        amount: null
      });
    }

  },
  // 计算距离
  getDistance: function(lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0.0;
    lng1 = lng1 || 0.0;
    lat2 = lat2 || 0.0;
    lng2 = lng2 || 0.0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137.0;
    return (r * 2.0 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2.0), 2.0) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2.0), 2.0)))).toFixed(0.0)

  },
  callUmbrella: function() {
    var that = this;
    if (app.globalData.sessionId == null) {
      wx.showModal({
        title: '请先登录',
        content: '你尚未登录，请登录后再操作',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.redirectTo({
              url: '../user/login/login',
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      if (app.globalData.locationEnd == null && app.globalData.locationStart == null) {
        wx.showToast({
          title: '请先规划路线',
          icon: 'none',
          duration: 2000
        })
      } else {
        if (this.data.amount > 8.0) {
          // 目前是校园平台，不允许订单金额大雨15元的订单下单
          wx.showModal({
            title: '禁止下单',
            content: '您的路程较远，订单金额大于8元\n请重新规划路线',
          });
        } else {
          // 把起始与结束位置的名称发出去，还有两个位置的经纬度。数据仅作为顾客
          var umbrellaType = that.data.umbrellaArray[that.data.index];
          wx.request({
            url: 'http://' + app.globalData.host + '/create/order',
            data: {
              locationStart: app.globalData.locationStart,
              locationEnd: app.globalData.locationEnd,
              latitudeStart: app.globalData.latitudeStart,
              longitudeStart: app.globalData.longitudeStart,
              latitudeEnd: app.globalData.latitudeEnd,
              longitudeEnd: app.globalData.longitudeEnd,
              distance: app.globalData.distance,
              sessionId: app.globalData.sessionId,
              umbrellaType: umbrellaType
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            method: 'POST',
            success: function(res) {
              if (res.data.code == 0) {
                wx.showModal({
                  title: '请先登录',
                  content: res.data.msg,
                  success: function(res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      wx.redirectTo({
                        url: '../user/login/login',
                      })
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                      wx.reLaunch({
                        url: './index',
                      })
                    }
                  }
                })
              } else if (res.data.code == 3) {
                wx.showModal({
                  title: '禁止下单',
                  content: res.data.msg,
                  success: function(res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      wx.navigateTo({
                        url: '/pages/orders/myOrders/myOrders',
                      });
                    } else if (res.cancel) {

                    }
                  }
                })
              } else {
                wx.showToast({
                  title: '订单发布成功',
                  icon: 'success',
                  duration: 2000
                });
                that.setData({
                  publish: true
                })
                // 前往我的订单页
                wx.navigateTo({
                  url: '../orders/myOrders/myOrders',
                  success: function() {
                    // 清空首页位置、距离、价格信息
                    app.globalData.locationStart = null;
                    app.globalData.locationEnd = null;
                  }
                });
              }
            },
            fail: function() {}
          });
        }

      }
    }
  },
  extendFunction: function() {
    wx.showToast({
      title: '尚未开通',
      icon: 'loading',
      duration: 400
    })
  }
})